package com.ibpd.shopping.web.controller.manage;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.henuocms.common.KVClass;
import com.ibpd.henuocms.common.ListSortUtil;
import com.ibpd.henuocms.web.controller.manage.BaseController;
import com.ibpd.shopping.assist.ExtSellInfo;
import com.ibpd.shopping.entity.OrderEntity;
import com.ibpd.shopping.entity.OrderdetailEntity;
import com.ibpd.shopping.entity.TenantEntity;
import com.ibpd.shopping.service.order.IOrderService;
import com.ibpd.shopping.service.order.OrderServiceImpl;
import com.ibpd.shopping.service.orderDetail.IOrderdetailService;
import com.ibpd.shopping.service.orderDetail.OrderdetailServiceImpl;
import com.ibpd.shopping.service.tenant.ITenantService;
import com.ibpd.shopping.service.tenant.TenantServiceImpl;

@Controller
public class Sell extends BaseController {
	@RequestMapping("Manage/Sell/index.do")
	public String index(Model model,HttpServletRequest req) throws IOException{
		model.addAttribute(PAGE_TITLE,"销售报表");
		ITenantService tenServ=(ITenantService) getService(TenantServiceImpl.class);
//		List<TenantEntity> tenList=tenServ.getList();//这里可以调用 重载把排序和检索做一下
		List<TenantEntity> tenList=tenServ.getList("from "+tenServ.getTableName()+" where status="+TenantEntity.TenantStatus_passed, null);
		model.addAttribute("tenantList",tenList);
		return "manage/s_sell/index";
	}
	@RequestMapping("Manage/Sell/getSellReport.do")
	public void getSellReport(Date startDate,Date endDate,Long tenantId,HttpServletResponse resp,HttpServletRequest req) throws IOException{
		if(startDate==null || endDate==null || tenantId==null){
			super.printParamErrorMsg(resp);
			return;
		}
		IOrderService ordServ=(IOrderService) getService(OrderServiceImpl.class);
		List<OrderEntity> orderList=ordServ.getRangeOrderList(startDate,endDate);
		if(orderList==null || orderList.size()==0){
			super.printMsg(resp, "-1", "-1", "该条件下没有订单");
			return;
		}
		IOrderdetailService detaServ=(IOrderdetailService) getService(OrderdetailServiceImpl.class);
		List<OrderdetailEntity> detaList=new ArrayList<OrderdetailEntity>();
		//下面的循环是将所有的订单详细信息汇总到一起
		for(OrderEntity order:orderList){
			List<OrderdetailEntity> tmp=detaServ.getListByOrderId(order.getId());
			if(tmp!=null && tmp.size()>0){
				for(OrderdetailEntity d:tmp){
					detaList.add(d);
				}
			}
		}
		//汇总完了,接下来就该正式做数据的汇总了
		//先把商户 取出来
		List<Long> tenantIdList=new ArrayList<Long>();
		
		if(tenantId==-1){
			//所有商户的订单一起汇总
			Map<Long,String> tenantIdMap=new HashMap<Long,String>();
			for(OrderdetailEntity d:detaList){
				tenantIdMap.put(d.getTenantId(), "");
			}
			Set<Long> idset=tenantIdMap.keySet();
			Iterator<Long> _s=idset.iterator();
			while(_s.hasNext()){
				tenantIdList.add(_s.next());
			}
			//取ID的代码有点繁琐了，有时间了简化
		}else if(tenantId==0){
			//总部的订单一起汇总
			tenantIdList.clear();
			tenantIdList.add(-1L);
		}else{
			//单独商户的订单汇总
			tenantIdList.clear();
			tenantIdList.add(tenantId);
		}
		//具体商户确定了，接下来从明细里过滤要 汇总的信息并顺便汇总
		List<ExtSellInfo> sellList=new ArrayList<ExtSellInfo>();
		for(OrderdetailEntity deta:detaList){
			for(Long tId:tenantIdList){
				deta.setTenantId(deta.getTenantId()==null?-99L:deta.getTenantId());
				if(deta.getTenantId().equals(tId)){
					ExtSellInfo sell=new ExtSellInfo();
					sell.setEndDate(endDate);
					sell.setNumber(deta.getNumber());
					sell.setOrderId(deta.getOrderID());
					sell.setPrice_d(deta.getPrice());
					sell.setProductName(deta.getProductName());
					sell.setStartDate(startDate);
					sell.setTenantId(deta.getTenantId());
					sell.setTotal_d(deta.getTotal());
					sellList.add(sell);
				}
			}
		}
		sellList=fillSellList(sellList);
		ListSortUtil sortUtil=new ListSortUtil();
		sortUtil.sort(sellList, "tenantId", "asc");
		List<KVClass> total=totalMap(sellList);
		JSONArray j=JSONArray.fromObject(sellList);
		JSONArray t=JSONArray.fromObject(total);
		super.printJsonData(resp, "({total:"+t.toString()+",rows:"+j.toString()+"})");
	}
	private List<KVClass> totalMap(List<ExtSellInfo> lst){
		Map<String,Double> rtnmap=new LinkedHashMap<String,Double>();
		for(ExtSellInfo sell:lst){
			rtnmap.put(sell.getTenantName(), sell.getTotal_d()+(rtnmap.get(sell.getTenantName())==null?0d:rtnmap.get(sell.getTenantName())));
		}
		List<KVClass> rtnlist=new ArrayList<KVClass>();
		DecimalFormat df = new DecimalFormat("#.00");
		for(String key:rtnmap.keySet()){
			KVClass kv=new KVClass();
			kv.setK(key);
			kv.setV(df.format(rtnmap.get(key)));
			rtnlist.add(kv);
		}
		return rtnlist;
	}
	private List<ExtSellInfo> fillSellList(List<ExtSellInfo> sellList){
		List<ExtSellInfo> rtnList=new ArrayList<ExtSellInfo>();
		if(sellList==null)
			return null;
		ITenantService ts=(ITenantService) getService(TenantServiceImpl.class);
		Map<Long,TenantEntity> tmap=new HashMap<Long,TenantEntity>();
		for(ExtSellInfo info:sellList){
			if(tmap.containsKey(info.getTenantId())){
				info.setTenantName(tmap.get(info.getTenantId()).getEntFullName());
			}else{
				if(info.getTenantId()!=-1L){
					TenantEntity t=ts.getEntityById(info.getTenantId());
					if(t!=null){
						tmap.put(info.getTenantId(), t);
						info.setTenantName(t.getEntFullName());
					}
				}else{
					info.setTenantName("总部平台");
				}
			}
			rtnList.add(info);
		}
		return rtnList;
	}
}